`include "timescale.v"

module ahb_ram_if(
	input 		   hresetn,
	input 		   hclk,
	input 		   hsel,	
	
	input  [31:0]  haddr,
	input  [1:0]   htrans,
	input 		   hwrite,
	input  [2:0]   hsize,
	input [2:0]   hburst,
	input [3:0]   hprot,
	input [31:0]  hwdata,
	
	// output 		   hsel,

	output [1:0]   hresp,
	output reg 	   hready,
	output reg  [31:0] hrdata 
	);


assign 			  hresp 	  = 2'b00;

reg 	  [31:0]  ram_addr;
always@(posedge hclk or negedge hresetn)
begin
  if(!hresetn)
  begin
	ram_addr <= 32'd0;
  end
  else if(hsel == 1'b1) begin					//delay for one clk
	ram_addr <= haddr;
  end
end

// ram write  (delay for one clk)
wire 			  wr_en;
assign 			  wr_en 	  = hsel & htrans[1] & hwrite;
reg 			  ram_write;
always@(posedge hclk or negedge hresetn)
begin
  if(!hresetn) begin
    ram_write <= 1'b0;
  end else if(wr_en) begin
    ram_write <= 1'b1;
  end else begin
    ram_write <= 1'b0;
  end
end

wire 			  ram_read;
assign 			  ram_read 	  = hsel & htrans[1] & ~hwrite; //no need to delay

wire 			  ready_en;
assign 			  ready_en 	  = hsel & htrans[1];
always@(posedge hclk or negedge hresetn)				//delay for one clk
begin
  if(!hresetn) begin
    hready <= 1'b0;
  end else if(ready_en) begin
    hready <= 1'b1;
  end else begin
    hready <= 1'b0;
  end
end


//the interface for PLI
always@(posedge hclk) begin
  if(ram_write)
  begin
	#1 $ahb_ram_write(ram_addr, hwdata, hsize);
  end
end

// always@(posedge hclk) begin
//   if(ram_read)
// 	$ahb_ram_read(ram_addr, hrdata);			//already delayed for read !!!
// end

always@(ram_addr)
begin
  #1 $ahb_ram_read(ram_addr, hrdata, hsize);
end


endmodule // ram_interface



